/***************************************************************************
 *   Copyright 2011 by Pardus Topluluğu                                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA .        *
 ***************************************************************************/


#include "nazar.h"

#include <QFontMetrics>
#include <QtCore/QSizeF>
#include <QtGui/QPainter>
#include <QtGui/QDesktopWidget>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsSceneMouseEvent>

#include <KSharedConfig>
#include <KLocale>
#include <KStandardDirs>
#include <KIO/NetAccess>
#include <KMessageBox>
#include <KNotification>
#include <KConfigDialog>
#include <KStandardAction>
#include <KToolInvocation>
#include <KAction>

#include <plasma/svg.h>
#include <plasma/theme.h>

#include <stdlib.h>

#ifdef Q_CC_MSVC
#include <iso646.h>
#endif

nazar::nazar(QObject *parent, const QVariantList &args): 
    Plasma::Applet(parent, args),
    m_enableNazarAction(0),
    m_disableNazarAction(0),
    m_sendNazarAction(0)
{
    setHasConfigurationInterface(true);

    // default background
    // this will get us the standard applet background, for free!
    setBackgroundHints(NoBackground);

    // for fix aspect ratio issue on panel
    setAspectRatioMode(Plasma::Square);
    resize(200, 200);

    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(showErrors()));
}



nazar::~nazar()
{
    if (hasFailedToLaunch()) {
        // Do some cleanup here
    } else {
        // Save settings
    }
}

void nazar::init()
{
    protection_working = true;
    number_of_attacks = defated_attacks = 0;

    configChanged();

    createMenu();

    setActionState(Idle);

    Plasma::ToolTipManager::self()->registerWidget(this);
    Plasma::ToolTipManager::self()->setContent(this, toolTipData);
}

void nazar::setActionState(ActionState state)
{
    toolTipData = Plasma::ToolTipContent();
    toolTipData.setAutohide(true);

    switch (state ) {
        case Unset:
            toolTipData.setMainText(i18n("You are all alone!"));
            toolTipData.setSubText(i18n("Nazar isn't protect your computer from evil eyes."));
            toolTipData.setImage(KIcon("nazar"));
            break;
        case Idle:
            toolTipData.setMainText(i18n("No evil eye allowed!"));
            toolTipData.setSubText(i18n("Nazar is ready to protect your computer from evil eyes."));
            toolTipData.setImage(KIcon("nazar"));
            break;
        case IdleError:
            toolTipData.setSubText(i18n("Evil eye received and it harmed! %1 attacks received so far, %2 are defated.", number_of_attacks, defated_attacks));
            toolTipData.setImage(KIcon("dialog-cancel"));

            QTimer::singleShot(15000, this, SLOT(resetActionState()));
            m_timer->stop();
            break;
        case IdleSuccess:
            toolTipData.setSubText(i18n("Evil eye received and eliminated successfuly. %1 attacks received so far, %2 are defated.", number_of_attacks, defated_attacks));
            toolTipData.setImage(KIcon("dialog-ok"));

            QTimer::singleShot(15000, this, SLOT(resetActionState()));
            m_timer->stop();
            break;
        case Sending:
            toolTipData.setSubText(i18n("Evil eye sending..."));
            toolTipData.setImage(KIcon("view-history"));
            break;
        default:
            break;
    }

    Plasma::ToolTipManager::self()->setContent(this, toolTipData);
    m_actionState = state;
    update();
}

void nazar::showErrors()
{
    setActionState(IdleError);
}

void nazar::resetActionState()
{
    setActionState(Idle);
    update();
}

void nazar::paintInterface(QPainter *p,
        const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
    if (m_nazarPixmap.isNull())
        return;

    p->setRenderHint(QPainter::SmoothPixmapTransform);
    p->setRenderHint(QPainter::Antialiasing);

    // Now we draw the applet, starting with our svg
    m_nazarSvg.resize((int)contentsRect.width(), (int)contentsRect.height());
    m_nazarSvg.paint(p, (int)contentsRect.left(), (int)contentsRect.top());
}

void nazar::createMenu()
{
    m_enableNazarAction = new QAction(SmallIcon("list-add"),i18n("&Enable nazar"), this);
    m_actions.append(m_enableNazarAction);
    connect(m_enableNazarAction, SIGNAL(triggered(bool)), this , SLOT(slotEnableNazar()));
    m_disableNazarAction = new QAction(SmallIcon("list-remove"),i18n("&Disable nazar"), this);
    m_actions.append(m_disableNazarAction);
    connect(m_disableNazarAction, SIGNAL(triggered(bool)), this , SLOT(slotDisableNazar()));
    m_sendNazarAction = new QAction(SmallIcon("tools-wizard"),i18n("&Send nazar"), this);
    m_actions.append(m_sendNazarAction);
    connect(m_sendNazarAction, SIGNAL(triggered(bool)), this , SLOT(slotSendNazar()));

    if (m_enableNazarAction >= 0) {
        m_enableNazarAction->setEnabled(false);
    } else if (m_disableNazarAction >= 0) {
        m_disableNazarAction->setEnabled(false);
    }
}

QList<QAction*> nazar::contextualActions()
{
    return m_actions;
}

void nazar::slotEnableNazar()
{
    m_disableNazarAction->setEnabled(true);
    m_enableNazarAction->setEnabled(false);

    setActionState(Idle);
    protection_working = true;

    KMessageBox::information(0, i18n("Nazar is starting to protect your computer from evil eyes..."));
}

void nazar::slotDisableNazar()
{
    m_enableNazarAction->setEnabled(true);
    m_disableNazarAction->setEnabled(false);

    setActionState(Unset);
    protection_working = false;

    KMessageBox::sorry(0, i18n("Nazar is stopping to protect your computer from evil eyes..."));
}

void nazar::slotSendNazar()
{
    ++number_of_attacks;

    if (is_protecting())
    {
        ++defated_attacks;
        setActionState(IdleSuccess);
        update();
    }
    else
    {
        setActionState(IdleError);
        update();
    }
}

void nazar::createConfigurationInterface(KConfigDialog *parent)
{
    QWidget *widget = new QWidget;
    ui.setupUi(widget);

    // Appearance
    ui.imageUrl->setUrl(KUrl::fromPath(m_image_url));

    parent->addPage(widget, i18n("General"), icon());
    connect(parent, SIGNAL(accepted()), this, SLOT(configurationChanged()));
}


void nazar::configurationChanged()
{
    KConfigGroup cg = config();

    // Appearance
    if (KIO::NetAccess::exists(ui.imageUrl->url(), KIO::NetAccess::SourceSide, NULL)) {
        m_image_url = ui.imageUrl->url().path();
        cg.writeEntry("ImgURL", m_image_url);
        m_nazarSvg.setImagePath(m_image_url);
    } else
        KMessageBox::error(0, i18n("The given image could not be loaded. The image will not be changed."));
    updateScalednazarImage();
    update();
}

void nazar::configChanged()
{
    KConfigGroup cg = config ();

    // Appearance
    m_image_url = cg.readEntry("ImgURL", KStandardDirs::locate("data", QLatin1String( "nazar/boncuk-01.svg" )));
    m_nazarSvg.setImagePath(m_image_url);

    updateScalednazarImage();
}


void nazar::updateScalednazarImage()
{
    // regen m_nazarPixmap
    m_nazarPixmap = m_nazarSvg.pixmap();

    // tint the pixmap if requested
    QPainter p(&m_nazarPixmap);
    p.setRenderHint(QPainter::Antialiasing, true);
    p.setPen(Qt::NoPen);
}

bool nazar::is_protecting()
{
    return protection_working;
}

#include "nazar.moc"
